import { Injectable } from '@angular/core';
import { Gif } from './gif'
//import 'rxjs/add/operator/toPromise';
//import resolve = require("resolve");

declare var Bmob:any;

const BMOB_APPID = '577c1d297b9dd58bdcfaa98da0c4d35d';
const BMOB_APIKEY = '1925d36e44bae96c58b811269925bd4e';
const EACH_PAGE_COUNT = 5;

let gifList = [];

@Injectable()
export class GifserviceService {

  constructor() {
    Bmob.initialize(BMOB_APPID, BMOB_APIKEY);
  }


  public getGifList(page:number):Promise <Gif[]> {

    var bmobGif = Bmob.Object.extend("Content");
    var query = new Bmob.Query(bmobGif);
    query.descending('createdAt');
    query.limit(EACH_PAGE_COUNT);
    query.skip(EACH_PAGE_COUNT * page);

    return query.find()
      .then((results) => {
        for (var i = 0; i < results.length; i++) {
          var object = results[i];
          var thumbImage = object.get('thumbImage');
          var thumbUrl: string;
          if (thumbImage == null) {
            thumbUrl = '';
          } else {
            thumbUrl = thumbImage._url;
          }
          var imageFile = object.get('imageFile');
          let tempGif = new Gif(object.id, thumbUrl, imageFile._url, '', '');
          gifList.push(tempGif);
        }
          return gifList;
      },
        (error) => {
          return Bmob.Promise.error('error.code + " " + error.message');
        }
      );



    // query.find({
    //  success: function (results) {
    //    for (var i = 0; i < results.length; i++) {
    //      var object = results[i];
    //      var thumbImage = object.get('thumbImage');
    //      var thumbUrl: string;
    //      if (thumbImage == null) {
    //        thumbUrl = '';
    //      } else {
    //        thumbUrl = thumbImage._url;
    //      }
    //      var imageFile = object.get('imageFile');
    //      let tempGif = new Gif(object.id, thumbUrl, imageFile._url, '', '');
    //      gifList.push(tempGif);
    //    }
    //    return gifList;
    //  }, error: function (error) {
    //    alert("查询失败: " + error.code + " " + error.message);
    //  }
    //});
    //
    //return gifList;
    /*

     return [

     new Gif(
     '000001',
     'http://img4.cache.netease.com/travel/2014/10/21/201410211618489fe54.jpg',
     'http://img4.cache.netease.com/travel/2014/10/21/201410211618489fe54.jpg',
     'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=27209829,2005944323&fm=21&gp=0.jpg',
     '名字1'
     ),
     new Gif(
     '000002',
     'http://img4.cache.netease.com/travel/2016/7/29/2016072918312813bfb.jpg',
     'http://img4.cache.netease.com/travel/2016/7/29/2016072918312813bfb.jpg',
     'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=400446162,3574831951&fm=58',
     '名字2'
     ),
     new Gif(
     '000003',
     'http://img5.cache.netease.com/travel/2016/7/29/20160729182512bc7e4.jpg',
     'http://img5.cache.netease.com/travel/2016/7/29/20160729182512bc7e4.jpg',
     '',
     '名字3'
     )
     ];*/
  }

}
